package web.util.email;

import org.apache.log4j.Logger;
import util.DateUtil;
import util.PropertiesUtil;

import java.io.File;
import java.io.IOException;

public class EmailUtil {
	private final static Logger LOGGER=Logger.getLogger("EmailUtil.class");
	
	
	public static void startEmail(String str,String user){
		MailSender ms=new MailSender();
		Email email=new Email();
		//email.setFromAddress("cheng_chao_cc@163.com");
		email.setFromAddress("qq378218251@163.com");
		email.setSubject("心跳检测：  "+ DateUtil.getDateToStr("yyyy-MM-dd", DateUtil.getNowToDate()));
		email.setContent(str);
		try {
			PropertiesUtil p=new PropertiesUtil();
			String [] emails=p.readValue(user).split(" ");
			
			for(int i=0;i<emails.length;i++){
				//System.out.println(emails[i]);
				LOGGER.info("- toEmail -"+emails[i]);
				email.setToAddress(emails[i]);
				ms.sendErrorMail(email);
				//测试发送html邮件
				//ms.sendHtmlMail(email);
			}
			LOGGER.info("- end toEmail -");
		} catch (IOException e) {
			e.printStackTrace();
		}	
	}


	/**
	 * 发送带附件的邮件
	 * @param str 邮件内容
	 * @param user 收件人
	 * @param subject 邮件标题
	 * @param file 附件
	 */
	public static boolean sendEmailFJ(String str,String user,String subject,File file){
		try{
			MailSender ms=new MailSender();
			Email email=new Email();
			//email.setFromAddress("cheng_chao_cc@163.com");
			email.setFromAddress("qq378218251@163.com");
			email.setSubject(subject+":"+DateUtil.getDateToStr("yyyy-MM-dd", DateUtil.getNowToDate()));
			email.setContent(str);
			email.setToAddress(user);
			ms.sendAccessoryMail(email,file);
			LOGGER.info("- 发送一键通邮件  To："+user+" -");
			return true;
		}catch (Exception e){
			LOGGER.error("发送一键通邮件【失败】,目标地址"+user+","+e);
			return false;
		}


	}
	public static boolean sendEmailFJ(String str,String user,String subject,String filePath){
		return sendEmailFJ(str,user,subject,new File(filePath));
	}



	public static void main(String[] args) {
		sendEmailFJ("HELLO", "378218251@qq.com", "test", "C:\\Users\\Administrator\\Desktop\\十月\\1014\\每日.xlsx");
	}


	
	/**
	 * 在邮件发送失败时，给管理员发送邮件提醒
	 * @param email
	 */
	public static void toAdminEmail(Email email){
		MailSender ms=new MailSender();
		String s="邮件标题："+email.getSubject()+"; 目标地址："+email.getToAddress()+"; ";
		email.setFromAddress("qq378218251@163.com");
		email.setSubject("邮件发送失败提醒");
		email.setContent(s);
		
		try {
			PropertiesUtil p=new PropertiesUtil();
			String [] emails=p.readValue("admin").split(" ");
			for(int i=0;i<emails.length;i++){
				LOGGER.info("-start-邮件发送失败给管理员发送邮件："+emails[i]);
				email.setToAddress(emails[i]);
				ms.sendErrorMail(email);
				//测试发送html邮件
				//ms.sendHtmlMail(email);
			}
			LOGGER.info("-end-给管理员发送邮件结束 -");
		} catch (IOException e) {
			e.printStackTrace();
		}	
	}
	
}
